package com.hk.api.outpainting;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.hk.api.outpainting.vo.CreateOutPaintingTaskRequest;
import com.hk.api.outpainting.vo.CreateOutPaintingTaskResponse;
import com.hk.api.outpainting.vo.GetOutPaintingTaskResponse;
import com.hk.exception.BusinessException;
import com.hk.exception.ErrorCode;
import com.hk.exception.ThrowExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云扩图API
 *
 * @author huangkun
 * @date 2025/1/17 14:06
 */
@Component
@Slf4j
public class ImageOutPaintService {

    @Value("${aliYun.accessKey}")
    private String accessKey;
    private static String CREATE_TASK_URL ="https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    private static String GET_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/";

    /**
     * 创建扩图任务
     *
     * @param createOutPaintingTaskRequest 创建扩图任务请求参数
     * @return
     */
    public CreateOutPaintingTaskResponse createTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        /**
         * 接口实例
         * curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting' \
         * --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
         * --header 'X-DashScope-Async: enable' \
         * --header 'Content-Type: application/json' \
         * --data '{
         *     "model": "image-out-painting",
         *     "input": {
         *         "image_url": "http://xxx/image.jpg"
         *     },
         *     "parameters":{
         *         "angle": 45,
         *         "x_scale":1.5,
         *         "y_scale":1.5
         *     }
         * }'
         */
        //发送请求
        HttpRequest request = HttpRequest.post(CREATE_TASK_URL)
                .header("Authorization", "Bearer " + accessKey)
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));

        try (HttpResponse response = request.execute()) {
            //判断响应是否成功
            if (!response.isOk()) {
                log.error("创建任务失败：{}", response.body());
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "创建任务失败");
            }
            //获取响应体
            String body = response.body();
            //解析响应体
            CreateOutPaintingTaskResponse taskResponse = JSONUtil.toBean(body, CreateOutPaintingTaskResponse.class);
            if (StrUtil.isNotBlank(taskResponse.getCode())) {
                log.error("创建任务失败：{}", taskResponse.getMessage());
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "创建任务失败");
            }
            return taskResponse;
        } catch (Exception e) {
            log.error("创建任务失败：{}", e.getMessage());
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "创建任务失败");
        }
    }

    /**
     * 根据taskId获取任务结果
     *
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponse getTaskResponse(String taskId) {
        /**
         * curl --location --request GET 'https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}' \
         * --header "Authorization: Bearer $DASHSCOPE_API_KEY"
         */
        ThrowExceptionUtil.throwIf(StrUtil.isBlank(taskId), ErrorCode.ERROR_PARAM, "taskId不能为空");
        try (
                HttpResponse response = HttpRequest.get(GET_TASK_URL + taskId)
                        .header("Authorization", "Bearer " + accessKey)
                        .execute();
        ) {
            if (!response.isOk()) {
                log.error("获取任务失败：{}", response.body());
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "获取任务失败");
            }
            log.error("获取任务成功：{}", response.body());
            return JSONUtil.toBean(response.body(), GetOutPaintingTaskResponse.class);

        } catch (Exception e) {
            log.error("获取任务失败：{}", e.getMessage());
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "获取任务失败");
        }
    }
}
